package com.lvcoding.customize.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.oauth2.provider.AuthorizationRequest;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author wuyanshen
 * @description 描述
 * @date 2022-02-21 上午11:49
 */
@RequestMapping("token")
@Controller
public class TokenEndpoints {

    /**
     * 自定义登录页面
     *
     * @param
     * @return java.lang.String
     */
    @GetMapping("login")
    public String login() {
        return "login";
    }


    /**
     * 自定义授权页面
     *
     * @param
     * @return ModelAndView
     */
    @GetMapping("confirm_access")
    public ModelAndView confirm(HttpServletRequest request, HttpSession session, ModelAndView modelAndView) {
        Map<String, Object> scopeList = (Map<String, Object>) request.getAttribute("scopes");
        Set<String> collect = scopeList.keySet().stream().map(item -> {
            String str = item.split("\\.")[1];
            return str;
        }).collect(Collectors.toSet());
        modelAndView.addObject("scopeList", collect);

        Object auth = session.getAttribute("authorizationRequest");
        if (auth != null) {
            AuthorizationRequest authorizationRequest = (AuthorizationRequest) auth;
            String clientId = authorizationRequest.getClientId();
            modelAndView.addObject("clientId", clientId);
            // Set<String> scope = authorizationRequest.getScope();
            // modelAndView.addObject("scopeList", scope);

            User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            modelAndView.addObject("user", user);
        }

        modelAndView.setViewName("approval");
        return modelAndView;
    }
}
